package com.zhao.fishingguideserver.controller;

import com.zhao.fishingguideserver.POJO.AdminUser;
import com.zhao.fishingguideserver.POJO.Result;
import com.zhao.fishingguideserver.service.AdminAuthService;
import com.zhao.fishingguideserver.utils.ThreadLocalUtil;
import jakarta.validation.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
import java.util.List;

/**
 * 管理员认证控制器
 */
@RestController
@Validated
@RequestMapping("/admin/auth")
public class AdminAuthController {
    
    @Autowired
    private AdminAuthService adminAuthService;
    
    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public Result<Map<String, String>> login(@RequestParam @NotEmpty String username,
                                              @RequestParam @NotEmpty String password) {
        try {
            String token = adminAuthService.login(username, password);
            Map<String, String> data = new HashMap<>();
            data.put("token", token);
            return Result.success(data);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取当前管理员信息
     */
    @GetMapping("/info")
    public Result<Map<String, Object>> getAdminInfo() {
        try {
            Map<String, Object> claims = ThreadLocalUtil.get();
            if (claims == null || claims.get("adminId") == null) {
                return Result.error("未登录或登录已过期");
            }
            
            Long adminId = ((Number) claims.get("adminId")).longValue();
            AdminUser adminUser = adminAuthService.findById(adminId);
            
            if (adminUser == null) {
                return Result.error("管理员不存在");
            }
            
            // 不返回密码
            adminUser.setPassword(null);

            // 基于角色生成权限点（可替换为数据库驱动）
            List<String> permissions;
            String role = adminUser.getRole();
            if ("super".equalsIgnoreCase(role) || "admin".equalsIgnoreCase(role)) {
                permissions = Arrays.asList(
                        "dashboard:view",
                        "user:list",
                        "user:update",
                        "user:delete",
                        "product:list",
                        "order:list",
                        "shop:stats",
                        "post:list",
                        "comment:list",
                        "community:stats",
                        "admin:list",
                        "log:list",
                        "system:settings"
                );
            } else {
                // 受限管理员
                permissions = Arrays.asList(
                        "dashboard:view",
                        "user:list",
                        "product:list",
                        "order:list",
                        "post:list",
                        "comment:list"
                );
            }

            Map<String, Object> data = new HashMap<>();
            data.put("admin", adminUser);
            data.put("permissions", permissions);
            return Result.success(data);
        } catch (Exception e) {
            return Result.error("获取管理员信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员登出
     */
    @PostMapping("/logout")
    public Result<Void> logout() {
        // JWT Token是无状态的，登出操作主要在前端删除Token
        // 如果需要服务端管理Token黑名单，可以在这里实现
        return Result.success();
    }
}

